<template>
  <div class="outbound-create">
    <el-page-header content="新增出库单" @back="router.back" style="margin-bottom: 16px" />

    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <span class="card-title">基础信息</span>
        </div>
      </template>
      <el-form ref="formRef" :model="form" label-width="auto" style="max-width: 1000px">
        <el-container>
          <el-aside width="500px">
            <el-form-item label="出库单号">
              <el-input v-model="form.outboundCode" placeholder="自动获取系统编号" class="readonly-input" readonly>
                <template #append>
                  <el-button @click="generateCode" :loading="generatingCode">自动生成</el-button>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item label="仓库名称">
              <el-select v-model="form.warehouseId" placeholder="请选择" style="width: 100%"
                :disabled="autoWarehouseOptions.length === 1" @change="handleWarehouseChange">
                <el-option v-for="item in (autoWarehouseOptions.length > 0 ? autoWarehouseOptions : warehouseOptions)"
                  :key="item.warehouseId" :label="item.warehouseName" :value="String(item.warehouseId)" />
              </el-select>
              <div v-if="linkSalesOrder && autoWarehouseOptions.length > 0" class="warehouse-info" :class="{
                'info-auto': warehouseSelectionInfo.type === 'auto',
                'info-multiple': warehouseSelectionInfo.type === 'multiple'
              }">
                <el-icon>
                  <InfoFilled />
                </el-icon>
                {{ warehouseSelectionInfo.message }}
              </div>
            </el-form-item>
            <el-form-item label="关联单号">
              <el-input v-model="form.salesOrderNo" placeholder="请选择销售单号" readonly style="cursor: pointer"
                @click="openSalesOrderDialog" :disabled="!linkSalesOrder">
                <template #append>
                  <el-button icon="Search" @click="openSalesOrderDialog" :disabled="!linkSalesOrder">
                    选择
                  </el-button>
                  <el-button v-if="isSalesOrderLinked" icon="Close" @click="clearSalesOrder"
                    :disabled="!linkSalesOrder" />
                </template>
              </el-input>
            </el-form-item>
            <el-form-item label="收货人">
              <el-input v-model="form.receiver" placeholder="请输入收货人" :disabled="linkSalesOrder" />
            </el-form-item>
            <el-form-item label="客户名称">
              <el-input v-model="form.customerName" placeholder="请输入客户名称" :disabled="linkSalesOrder" />
            </el-form-item>

          </el-aside>

          <el-aside width="500px" style="margin-left: 28px;">
            <el-form-item label="出库类型">
              <el-select v-model="form.outboundTypeId" placeholder="请选择" style="width: 100%">
                <el-option v-for="item in outboundTypeOptions" :label="item.warehousingName"
                  :value="item.warehousingTypeId" />
              </el-select>
            </el-form-item>
            <el-form-item label="出库日期">
              <el-date-picker v-model="form.outboundDate" type="date" placeholder="请选择日期" style="width: 100%" />
            </el-form-item>
            <el-form-item>
              <el-checkbox v-model="linkSalesOrder" @change="handleLinkSalesOrderChange">
                关联销售单号
              </el-checkbox>
            </el-form-item>
            <el-form-item label="经办人">
              <el-input v-model="selectedHandlerName" placeholder="请选择经办人" readonly style="cursor: pointer"
                @click="openUserDialog">
                <template #append>
                  <el-button icon="Search" @click="openUserDialog">选择</el-button>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item label="联系方式">
              <el-input v-model="form.contactInformation" placeholder="请输入联系方式" :disabled="linkSalesOrder" />
            </el-form-item>
          </el-aside>
        </el-container>
        <el-form-item label="备注">
          <el-input v-model="form.outboundDescription" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
    </el-card>

    <el-card shadow="never" style="margin-top: 16px">
      <template #header>
        <div class="card-header">
          <span class="card-title">出库明细</span>
          <el-button type="primary" @click="addDetail">新增</el-button>
        </div>
      </template>

      <el-table :data="details" border style="width: 100%">
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="productName" label="货品名称" width="140">
          <template #default="scope">
            <el-input v-model="scope.row.productName" size="small" placeholder="请输入货品名称" />
          </template>
        </el-table-column>
        <el-table-column prop="productCode" label="货品编号" width="140">
          <template #default="scope">
            <el-input v-model="scope.row.productCode" size="small" placeholder="请输入货品编号" />
          </template>
        </el-table-column>
        <el-table-column prop="categoryName" label="货品类型" width="120">
          <template #default="scope">
            <el-input v-model="scope.row.categoryName" size="small" placeholder="请输入货品类型" />
          </template>
        </el-table-column>
        <el-table-column prop="spec" label="规格型号" width="120">
          <template #default="scope">
            <el-input v-model="scope.row.spec" size="small" placeholder="请输入规格型号" />
          </template>
        </el-table-column>
        <el-table-column prop="unit" label="单位" width="80">
          <template #default="scope">
            <el-input v-model="scope.row.unit" size="small" placeholder="单位" />
          </template>
        </el-table-column>
        <el-table-column prop="locationName" label="出库库区" width="140">
          <template #default="scope">
            <el-select v-if="scope.row.locationOptions && scope.row.locationOptions.length > 0"
              v-model="scope.row.storagelocationId" placeholder="请选择库区" size="small" style="width: 100%"
              @change="handleLocationChange(scope.row)">
              <el-option v-for="loc in scope.row.locationOptions" :key="loc.storagelocationId" :label="loc.locationName"
                :value="loc.storagelocationId" />
            </el-select>
            <el-input v-else v-model="scope.row.locationName" size="small" placeholder="请输入库区" readonly />
          </template>
        </el-table-column>
        <el-table-column prop="positionId" label="仓位" width="180">
          <template #default="scope">
            <el-select v-model="scope.row.positionId" placeholder="请选择仓位" size="small" style="width: 100%" clearable
              filterable :loading="scope.row.positionLoading" @focus="ensureDetailPositionOptions(scope.row)"
              @change="handleDetailPositionChange(scope.row)">
              <el-option v-for="pos in scope.row.positionOptions || []" :key="pos.value" :label="pos.label"
                :value="pos.value" :disabled="pos.isFull === false" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="oldStock" label="出库前库存" width="120" align="right">
          <template #default="scope">
            <el-input-number v-model="scope.row.oldStock" :min="0" size="small" :controls="false" />
          </template>
        </el-table-column>
        <el-table-column prop="deliveryPrice" label="销售单价" width="120" align="right">
          <template #default="scope">
            <el-input-number v-model="scope.row.deliveryPrice" :min="0" :precision="2" size="small" :controls="false"
              @change="recalcRow(scope.row)" />
          </template>
        </el-table-column>
        <el-table-column prop="deliveryNum" label="出库数量" width="120" align="right">
          <template #default="scope">
            <el-input-number v-model="scope.row.deliveryNum" :min="0" size="small" :controls="false"
              @change="recalcRow(scope.row)" />
          </template>
        </el-table-column>
        <el-table-column prop="totalDeliveryPrice" label="销售金额" width="140" align="right">
          <template #default="scope">
            ¥{{ scope.row.totalDeliveryPrice?.toFixed(2) || '0.00' }}
          </template>
        </el-table-column>
        <el-table-column prop="newStock" label="出库后库存" width="120" align="right">
          <template #default="scope">
            <el-input-number v-model="scope.row.newStock" :min="0" size="small" :controls="false" />
          </template>
        </el-table-column>
        <el-table-column prop="inputBatch" label="批次号" width="140">
          <template #default="scope">
            <el-input v-model="scope.row.inputBatch" size="small" placeholder="请输入批次号" />
          </template>
        </el-table-column>
        <el-table-column prop="inputTime" label="生产日期" width="150">
          <template #default="scope">
            <el-date-picker v-model="scope.row.inputTime" type="date" placeholder="选择日期" size="small"
              style="width: 100%" />
          </template>
        </el-table-column>
        <el-table-column prop="inputNote" label="备注" width="160">
          <template #default="scope">
            <el-input v-model="scope.row.inputNote" size="small" placeholder="请输入备注" />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="80" fixed="right">
          <template #default="scope">
            <el-button link type="danger" size="small" @click="removeDetail(scope.$index)">移除</el-button>
          </template>
        </el-table-column>
        <template #empty>
          <div class="empty-state">
            <p>暂无出库明细</p>
            <p>点击上方“新增”按钮添加货品</p>
          </div>
        </template>
      </el-table>

      <div class="summary-info">
        <span>合计：</span>
        <span style="margin-left: 20px;">出库数量：{{ totalQuantity }}</span>
        <span style="margin-left: 20px;">出库金额：¥{{ totalAmount.toFixed(2) }}</span>
      </div>
    </el-card>

    <el-card>
      <el-button type="success" style="float: right; margin-bottom: 15px;" @click="handleSave" :loading="saving">
        保存
      </el-button>
    </el-card>
  </div>

  <!-- 关联销售单弹窗 -->
  <el-dialog v-model="salesOrderDialogVisible" title="选择销售单" width="80%" :close-on-click-modal="false">
    <el-form :model="salesOrderSearchForm" :inline="true" class="search-form">
      <el-form-item label="销售单号">
        <el-input v-model="salesOrderSearchForm.salesOrderNo" placeholder="请输入销售单号" clearable />
      </el-form-item>
      <el-form-item label="单据状态">
        <el-select v-model="salesOrderSearchForm.salesOrderStatus" placeholder="请选择单据状态" clearable>
          <el-option v-for="item in salesOrderStatusOptions" :key="item.value" :label="item.label"
            :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="客户">
        <el-select v-model="salesOrderSearchForm.customerId" placeholder="请选择客户" filterable clearable>
          <el-option v-for="item in customerOptions" :key="item.customerId" :label="item.customerName"
            :value="item.customerId" />
        </el-select>
      </el-form-item>
      <el-form-item label="销售日期">
        <el-date-picker v-model="salesOrderSearchForm.dateRange" type="daterange" range-separator="至"
          start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSalesOrderSearch" :loading="salesOrderTableLoading">
          查询
        </el-button>
        <el-button @click="resetSalesOrderSearch">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table :data="salesOrderList" v-loading="salesOrderTableLoading" highlight-current-row
      @current-change="handleSalesOrderCurrentChange">
      <el-table-column type="index" label="序号" width="60" />
      <el-table-column label="选择" width="70">
        <template #default="scope">
          <el-radio v-model="selectedSalesOrderId" :label="scope.row.salesOrderId">
            &nbsp;
          </el-radio>
        </template>
      </el-table-column>
      <el-table-column prop="salesOrderNo" label="销售单号" width="140" />
      <el-table-column prop="salesOrderStatus" label="单据状态" width="100">
        <template #default="scope">
          {{ formatSalesOrderStatus(scope.row.salesOrderStatus) }}
        </template>
      </el-table-column>
      <el-table-column prop="salesOrderDate" label="销售日期" width="140">
        <template #default="scope">
          {{ formatDate(scope.row.salesOrderDate) }}
        </template>
      </el-table-column>
      <el-table-column prop="customerName" label="客户名称" min-width="140" />
      <el-table-column prop="organizationName" label="销售部门" min-width="140" />
      <el-table-column prop="userName" label="销售负责人" min-width="120" />
      <el-table-column prop="salesOrderQuantity" label="货品数量" width="120" align="right" />
      <el-table-column prop="salesOrderAmount" label="销售金额" width="140" align="right">
        <template #default="scope">
          {{ Number(scope.row.salesOrderAmount ?? 0).toFixed(2) }}
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container" style="margin-top: 12px">
      <div class="pagination-info">总{{ salesOrderPagination.total }}条</div>
      <el-pagination v-model:current-page="salesOrderPagination.pageindex"
        v-model:page-size="salesOrderPagination.pagesize" :page-sizes="[10, 20, 50, 100]"
        :total="salesOrderPagination.total" layout="prev, pager, next" @size-change="handleSalesOrderPageSizeChange"
        @current-change="handleSalesOrderPageIndexChange" />
      <el-select v-model="salesOrderPagination.pagesize" style="width: 100px; margin-left: 10px"
        @change="handleSalesOrderPageSizeChange">
        <el-option label="10条/页" :value="10" />
        <el-option label="20条/页" :value="20" />
        <el-option label="50条/页" :value="50" />
        <el-option label="100条/页" :value="100" />
      </el-select>
    </div>

    <template #footer>
      <el-button @click="salesOrderDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="confirmSalesOrderSelection" :disabled="!selectedSalesOrder">
        确定
      </el-button>
    </template>
  </el-dialog>

  <el-dialog v-model="userDialogVisible" title="选择人员" width="70%" :close-on-click-modal="false">
    <div class="user-selection-container">
      <div class="search-section">
        <el-input v-model="userSearchKeyword" placeholder="请输入姓名或编号" clearable
          style="width: 300px; margin-right: 10px;" />
        <el-button type="primary" @click="searchUsers" icon="Search">查询</el-button>
      </div>

      <div class="content-section">
        <div class="organization-tree">
          <div class="tree-header">组织架构</div>
          <el-tree :data="organizationTree" :props="treeProps" node-key="organizationId"
            @node-click="handleOrganizationClick" :expand-on-click-node="false" :highlight-current="true"
            v-loading="treeLoading">
            <template #default="{ data }">
              <span class="tree-node">{{ data.organizationName || data.label }}</span>
            </template>
          </el-tree>
        </div>

        <div class="user-list">
          <div class="list-header">
            已选择 {{ selectedUser ? 1 : 0 }} 人
            <el-tag v-if="selectedUser" closable @close="clearSelectedUser" class="selected-user-tag">
              {{ selectedUser.userName }}
            </el-tag>
          </div>
          <div class="user-grid" v-loading="userLoading">
            <div v-for="user in filteredUsers" :key="user.userId"
              :class="['user-item', { selected: selectedUser && selectedUser.userId === user.userId }]"
              @click="selectUser(user)">
              <div class="user-avatar">{{ user.userName?.charAt(0) }}</div>
              <div class="user-info">
                <div class="user-name">{{ user.userName }}</div>
                <div class="user-account">{{ user.userAccount }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="userDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmUserSelection" :disabled="!selectedUser">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 产品选择对话框 -->
  <el-dialog v-model="productDialogVisible" title="添加货品" width="60%" :close-on-click-modal="false">
    <!-- 搜索条件 -->
    <el-form :model="productSearchForm" :inline="true" class="search-form">
      <el-form-item label="货品编号/名称">
        <el-input v-model="productSearchForm.productName" placeholder="请输入货品编号/名称" clearable style="width: 200px" />
      </el-form-item>
      <el-form-item label="单位">
        <el-select v-model="productSearchForm.unitId" placeholder="请选择单位" clearable style="width: 150px">
          <el-option v-for="item in unitOptions" :key="item.unitId" :label="item.unitName" :value="item.unitId" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="searchProducts" icon="Search" :loading="productTableLoading">
          查询
        </el-button>
        <el-button @click="resetProductSearch" icon="Refresh">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 产品表格 -->
    <el-table :data="productList" style="width: 100%" @selection-change="handleProductSelection"
      v-loading="productTableLoading" height="400px">
      <el-table-column type="selection" width="55" />
      <el-table-column type="index" label="序号" width="60" />
      <el-table-column prop="productCode" label="货品编号" width="160" />
      <el-table-column prop="productName" label="货品名称" width="160" />
      <el-table-column prop="producttypeName" label="规格型号" width="160" />
      <el-table-column prop="productspecification" label="单位" width="160" />
      <el-table-column prop="productInmoney" label="销售单价" width="160" align="right">
        <template #default="scope">
          ¥{{ scope.row.productInmoney?.toFixed(2) || '0.00' }}
        </template>
      </el-table-column>
      <el-table-column prop="inventoryCurrtnumber" label="当前库存" width="120" align="right" />
      <el-table-column prop="warehouseName" label="仓库" width="120" />
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container" style="margin-top: 12px">
      <div class="pagination-info">总{{ productPagination.total }}条</div>
      <el-pagination v-model:current-page="productPagination.pageindex" v-model:page-size="productPagination.pagesize"
        :page-sizes="[10, 20, 50, 100]" :total="productPagination.total" layout="prev, pager, next"
        @size-change="handleProductPageSizeChange" @current-change="handleProductPageIndexChange" />
      <el-select v-model="productPagination.pagesize" style="width: 100px; margin-left: 10px"
        @change="handleProductPageSizeChange">
        <el-option label="10条/页" :value="10" />
        <el-option label="20条/页" :value="20" />
        <el-option label="50条/页" :value="50" />
        <el-option label="100条/页" :value="100" />
      </el-select>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="productDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmProductSelection" :disabled="selectedProducts.length === 0">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { computed, onMounted, reactive, ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { InfoFilled } from '@element-plus/icons-vue'
import moment from 'moment'
import { useRoute, useRouter } from 'vue-router'
import myaxios from '@/http/MyAxios'

interface LocationOption {
  storagelocationId: number
  locationName: string
  locationCode: string
  currentStock: number
}

interface ShelfInfo {
  shelfId: number
  shelfCode: string
  shelfName: string
  storagelocationId: number
}

interface PositionOption {
  value: number
  label: string
  shelfId: number
  shelfCode: string
  shelfName: string
  positionCode?: string
  positionRow?: number
  positionColumn?: number
  positionLayer?: number
  positionDepth?: number
  isFull?: boolean
}

interface OutboundDetailRow {
  productId?: number
  productCode: string
  productName: string
  categoryName: string
  spec: string
  unit: string
  locationName: string
  storagelocationId?: number
  locationOptions?: LocationOption[]
  positionId?: number | null
  positionOptions?: PositionOption[]
  positionLoading?: boolean
  oldStock: number
  deliveryPrice: number
  deliveryNum: number
  totalDeliveryPrice: number
  newStock: number
  inputBatch: string
  inputTime: string | Date | null
  inputNote: string
}

const router = useRouter()
const route = useRoute()

const formRef = ref()
const form = reactive({
  outboundId: '',
  outboundCode: '',
  outboundTypeId: '',
  outboundDate: '',
  warehouseId: '',
  salesOrderId: '',
  salesOrderNo: '',
  customerName: '',
  contactInformation: '',
  receiver: '',
  handlerProple: '',
  userId: '',
  organizationId: '',
  documentCreator: '张三',
  outboundDescription: '',
  documentCreation: ''
})

const details = ref<OutboundDetailRow[]>([])

const warehouseOptions = ref<any[]>([])
const autoWarehouseOptions = ref<any[]>([])
const outboundTypeOptions = ref([{
  "warehousingTypeId": '',
  "warehousingName": ""
}])
const customerOptions = ref<any[]>([])

const generatingCode = ref(false)
const saving = ref(false)
const SHELF_PAGE_SIZE = 9999
const POSITION_PAGE_SIZE = 999
const shelfCacheByWarehouse = reactive<Record<number, ShelfInfo[]>>({})
const positionCacheByShelf = reactive<Record<number, PositionOption[]>>({})

const isEdit = computed(() => !!route.query.outboundId)
const linkSalesOrder = ref(true)
const isSalesOrderLinked = computed(() => !!form.salesOrderId)

// 计算当前仓库选择状态
const warehouseSelectionInfo = computed(() => {
  if (autoWarehouseOptions.value.length === 0) {
    return { type: 'normal', message: '请选择仓库' }
  } else if (autoWarehouseOptions.value.length === 1) {
    return { type: 'auto', message: `已自动选择：${autoWarehouseOptions.value[0].warehouseName}` }
  } else {
    return { type: 'multiple', message: `找到 ${autoWarehouseOptions.value.length} 个仓库，请选择` }
  }
})

const addDetail = () => {
  // 如果没有关联单号，打开产品选择对话框
  if (!form.salesOrderId && !form.salesOrderNo) {
    openProductDialog()
  } else {
    // 如果有关联单号，直接添加空行
    details.value.push({
      productCode: '',
      productName: '',
      categoryName: '',
      spec: '',
      unit: '',
      locationName: '',
      oldStock: 0,
      deliveryPrice: 0,
      deliveryNum: 0,
      totalDeliveryPrice: 0,
      newStock: 0,
      inputBatch: '',
      inputTime: null,
      inputNote: '',
      positionId: null,
      positionOptions: [],
      positionLoading: false,
    })
  }
}

const removeDetail = (index: number) => {
  details.value.splice(index, 1)
}

const recalcRow = (row: OutboundDetailRow) => {
  row.totalDeliveryPrice = Number(row.deliveryPrice || 0) * Number(row.deliveryNum || 0)
}

const ensureDetailPositionMeta = (detail: OutboundDetailRow) => {
  if (!detail) return
  if (!Array.isArray(detail.positionOptions)) {
    detail.positionOptions = []
  }
  if (typeof detail.positionLoading !== 'boolean') {
    detail.positionLoading = false
  }
  if (detail.positionId === undefined) {
    detail.positionId = null
  }
}

const formatPositionParts = (position: any) => {
  const parts: string[] = []
  const appendPart = (value: number | null | undefined, suffix: string) => {
    if (typeof value === 'number' && !Number.isNaN(value) && value > 0) {
      parts.push(`${value}${suffix}`)
    }
  }
  appendPart(Number(position.positionRow ?? position.PositionRow), '排')
  appendPart(Number(position.positionColumn ?? position.PositionColumn), '列')
  appendPart(Number(position.positionLayer ?? position.PositionLayer), '层')
  appendPart(Number(position.positionDepth ?? position.PositionDepth), '深')
  return parts.length ? parts.join('') : ''
}

const buildPositionOptionLabel = (shelf: ShelfInfo | null, position: any) => {
  const descriptor = formatPositionParts(position) || position.positionCode || position.PositionCode || ''
  if (descriptor) return descriptor
  return shelf?.shelfCode || shelf?.shelfName || `仓位${position.positionId || ''}`
}

const totalQuantity = computed(() =>
  details.value.reduce((sum, item) => sum + Number(item.deliveryNum || 0), 0),
)

const totalAmount = computed(() =>
  details.value.reduce((sum, item) => sum + Number(item.totalDeliveryPrice || 0), 0),
)

// 编号生成相关
const TIME_SEGMENT_ORDER = ['YYYY', 'YY', 'MM', 'DD', 'HH', 'MI', 'SS']
const pad = (n: number, len = 2) => `${n}`.padStart(len, '0')

const buildCodeFromRule = (rule: any) => {
  const now = new Date()
  const segments = (rule?.timeRule || '')
    .split(',')
    .map((s: string) => s.trim().toUpperCase())
    .filter(Boolean)
    .sort((a: string, b: string) => {
      const idxA = TIME_SEGMENT_ORDER.indexOf(a)
      const idxB = TIME_SEGMENT_ORDER.indexOf(b)
      if (idxA === -1 && idxB === -1) return 0
      if (idxA === -1) return 1
      if (idxB === -1) return -1
      return idxA - idxB
    })
  const timePart = segments
    .map((seg: string) => {
      switch (seg) {
        case 'YYYY': return String(now.getFullYear())
        case 'YY': return String(now.getFullYear()).slice(-2)
        case 'MM': return pad(now.getMonth() + 1)
        case 'DD': return pad(now.getDate())
        case 'HH': return pad(now.getHours())
        case 'MI': return pad(now.getMinutes())
        case 'SS': return pad(now.getSeconds())
        default: return ''
      }
    })
    .join('')
  const serialLength = Number(rule?.serialLength ?? 3)
  const serial = '1'.padStart(serialLength > 0 ? serialLength : 3, '0')
  return `${rule?.codePrefix || ''}${timePart}${serial}`
}

const requestNumber = async (targetCode: string, targetName: string) => {
  try {
    // 直接使用 QueryNumberingRules 接口，参数使用 targetName
    const ruleRes = await myaxios.get('/api/Number/QueryNumberingRules', {
      params: { targetName }
    })
    const list = Array.isArray(ruleRes?.data?.data) ? ruleRes.data.data : []
    if (list.length > 0) {
      return buildCodeFromRule(list[0])
    }
    throw new Error('未找到对应的编号规则，请先配置编号规则')
  } catch (err: any) {
    console.error(`[numbering] 获取编号规则失败 (${targetName})`, err)
    throw new Error(err?.message || '获取编号规则失败，请先配置编号规则')
  }
}

const generateCode = async () => {
  if (generatingCode.value) return
  generatingCode.value = true
  try {
    form.outboundCode = await requestNumber('Outbound', '出库单')
    ElMessage.success('编号生成成功')
  } catch (error: any) {
    ElMessage.error(error?.message || '生成编号失败')
  } finally {
    generatingCode.value = false
  }
}

const loadWarehouses = async () => {
  try {
    const res = await myaxios.get('/api/Warehousing/GetWarehouse')
    if (res.data?.success || res.data?.code === 200) {
      warehouseOptions.value = res.data.data || []
    }
  } catch (error) {
    console.error('获取仓库列表失败:', error)
  }
}

const loadOutboundTypes = async () => {
  try {
    const res = await myaxios.get('/api/Outbound/GetOutboundType')
    if (res.data?.success || res.data?.code === 200) {
      outboundTypeOptions.value = res.data.data || []
    }
  } catch (error) {
    console.error('获取出库类型失败:', error)
  }
}

const loadCustomers = async () => {
  try {
    const res = await myaxios.get('/api/Customer/GetCustomer', {
      params: { pageindex: 1, pagesize: 1000 }
    })
    if (res.data?.success || res.data?.code === 200) {
      customerOptions.value = res.data.data?.data || res.data.data || []
    }
  } catch (error) {
    console.error('获取客户列表失败:', error)
  }
}

const loadForEdit = async () => {
  const outboundId = String(route.query.outboundId || '')
  if (!outboundId) return
  try {
    const res = await myaxios.get('/api/Outbound/GetOutboundDetail', {
      params: { outboundId },
    })
    const data = res.data?.data || {}
    form.outboundId = data.outboundId
    form.outboundCode = data.outboundCode
    form.outboundTypeId = data.outboundTypeId
    form.outboundDate = data.outboundDate
    form.warehouseId = data.warehouseId ? String(data.warehouseId) : ''
    form.salesOrderId = data.salesOrderId
    form.salesOrderNo = data.salesOrderNo
    form.customerName = data.customerName
    form.contactInformation = data.contactInformation
    form.receiver = data.receiver || data.salesContact || ''
    form.handlerProple = data.handlerProple
    selectedHandlerName.value = data.handlerProple || ''
    form.documentCreator = data.documentCreator
    form.outboundDescription = data.outboundDescription
    form.documentCreation = data.documentCreation || ''
    linkSalesOrder.value = Boolean(form.salesOrderId)

    const detailSource =
      data.detailList ||
      data.deliveryDetails ||
      data.outboundDetails ||
      []

    details.value = detailSource.map((item: any) => ({
      productId: item.productId,
      productCode: item.productCode || '',
      productName: item.productName || '',
      categoryName: item.categoryName || '',
      spec:
        item.spec ||
        item.specification ||
        item.productSpecification ||
        '',
      unit: item.unit || item.unitName || '',
      locationName:
        item.locationName ||
        item.storageLocationName ||
        '',
      storagelocationId: item.storagelocationId,
      oldStock: Number(item.oldStock ?? item.beforeStock ?? 0),
      deliveryPrice: Number(item.deliveryPrice ?? item.unitPrice ?? 0),
      deliveryNum: Number(item.deliveryNum ?? item.quantity ?? 0),
      totalDeliveryPrice: Number(
        item.totalDeliveryPrice ?? item.amount ?? item.currentAmount ?? 0,
      ),
      newStock: Number(item.newStock ?? item.afterStock ?? 0),
      inputBatch: item.inputBatch || item.batchNo || '',
      inputTime:
        item.inputTime ||
        item.productionDate ||
        item.generateDate ||
        '',
      inputNote: item.inputNote || item.remark || '',
      positionId: Number(item.positionId ?? item.PositionId ?? 0) || null,
      positionOptions: [],
      positionLoading: false,
    }))
    details.value.forEach(detail => ensureDetailPositionMeta(detail))
    if (form.warehouseId) {
      await queryStorageLocationsForAllDetails()
    }
  } catch (error) {
    console.error('加载出库单失败:', error)
    ElMessage.error('加载出库单失败')
  }
}

const handleSave = async () => {
  if (!details.value.length) {
    ElMessage.warning('请先添加出库明细')
    return
  }

  // 如果没有出库单号，自动生成
  if (!form.outboundCode) {
    try {
      await generateCode()
      if (!form.outboundCode) {
        ElMessage.warning('请先生成出库单号')
        return
      }
    } catch (error) {
      ElMessage.error('生成出库单号失败，请稍后重试')
      return
    }
  }

  saving.value = true
  try {
    // 确保日期格式正确，后端需要 DateTime 类型
    const outboundDate = form.outboundDate
      ? moment(form.outboundDate).format('YYYY-MM-DDTHH:mm:ss')
      : moment().format('YYYY-MM-DDTHH:mm:ss')

    const documentCreation = form.documentCreation
      ? moment(form.documentCreation).format('YYYY-MM-DDTHH:mm:ss')
      : moment().format('YYYY-MM-DDTHH:mm:ss')

    const payload: any = {
      outboundId: Number(form.outboundId) || 0,
      outboundCode: form.outboundCode || '',
      outboundTypeId: Number(form.outboundTypeId) || 0,
      outboundDate: outboundDate,
      warehousingCodeState: 1, // 默认待审核状态
      warehouseId: Number(form.warehouseId) || 0,
      salesOrderId: Number(form.salesOrderId) || 0,
      userId: Number(form.userId) || 0,
      productid: 0, // 出库单主表不需要产品ID
      outboundNum: totalQuantity.value,
      outboundMoney: Number(totalAmount.value.toFixed(2)),
      handlerProple: form.handlerProple || '',
      customerName: form.customerName || '',
      contactInformation: form.contactInformation || '',
      documentCreator: form.documentCreator || localStorage.getItem('username') || '系统',
      organizationId: Number(form.organizationId) || 0,
      documentCreation: documentCreation,
      outboundDescription: form.outboundDescription || '',
      supplierId: 0, // 出库单不需要供应商ID
      detailList: details.value.map((x) => ({
        productId: Number(x.productId) || 0,
        productCode: x.productCode || '',
        productName: x.productName || '',
        categoryName: x.categoryName || '',
        spec: x.spec || '',
        unit: x.unit || '',
        locationName: x.locationName || '',
        storagelocationId: Number(x.storagelocationId) || 0,
        oldStock: Number(x.oldStock) || 0,
        deliveryPrice: Number(x.deliveryPrice) || 0,
        deliveryNum: Number(x.deliveryNum) || 0,
        totalDeliveryPrice: Number(x.totalDeliveryPrice) || 0,
        newStock: Number(x.newStock) || 0,
        inputBatch: x.inputBatch || '',
        inputTime: x.inputTime
          ? moment(x.inputTime).format('YYYY-MM-DD')
          : null,
        inputNote: x.inputNote || '',
        positionId: Number(x.positionId) || 0,
      })),
    }

    const url = isEdit.value
      ? '/api/Outbound/UpdateOutbound'
      : '/api/Outbound/CreateOutbound'
    const method = isEdit.value ? 'put' : 'post'

    console.log('保存出库单，payload:', payload)

    const res = await myaxios({ url, method, data: payload } as any)

    if (res.data?.success || res.data?.code === 200) {
      ElMessage.success('保存成功')
      router.push('/GetOutbound')
    } else {
      const errorMsg = res.data?.message || res.data?.data || '保存失败'
      console.error('保存失败，响应:', res.data)
      ElMessage.error(errorMsg)
    }
  } catch (error: any) {
    console.error('保存失败:', error)
    const errorMsg = error?.response?.data?.message || error?.message || '保存失败，请稍后重试'
    ElMessage.error(errorMsg)
  } finally {
    saving.value = false
  }
}

onMounted(() => {
  loadWarehouses()
  loadOutboundTypes()
  loadCustomers()
  if (isEdit.value) {
    loadForEdit()
  }
})

interface SalesOrderDTO {
  salesOrderId: number
  salesOrderNo: string
  salesOrderStatus: number
  salesOrderDate: string
  customerName: string
  customerId: number
  organizationName: string
  userName: string
  salesOrderQuantity: number
  salesOrderAmount: number
  salesContact?: string
  salesContactPhone?: string
}

const salesOrderDialogVisible = ref(false)
const salesOrderList = ref<SalesOrderDTO[]>([])
const salesOrderTableLoading = ref(false)
const selectedSalesOrderId = ref<number | null>(null)
const selectedSalesOrder = ref<SalesOrderDTO | null>(null)
const salesOrderPagination = reactive({
  pageindex: 1,
  pagesize: 10,
  total: 0
})

const salesOrderStatusOptions = [
  { value: 0, label: '草稿' },
  { value: 1, label: '待审核' },
  { value: 2, label: '部分出库' },
  { value: 3, label: '已出库' },
  { value: 4, label: '已关闭' }
]

const salesOrderSearchForm = reactive({
  salesOrderNo: '',
  salesOrderStatus: undefined as number | undefined,
  customerId: '',
  dateRange: [] as string[]
})

const openSalesOrderDialog = () => {
  if (!linkSalesOrder.value) return
  salesOrderDialogVisible.value = true
  fetchSalesOrders()
}

const fetchSalesOrders = async () => {
  salesOrderTableLoading.value = true
  try {
    const params: any = {
      salesOrderNo: salesOrderSearchForm.salesOrderNo || undefined,
      salesOrderStatus: salesOrderSearchForm.salesOrderStatus,
      customerId: salesOrderSearchForm.customerId || undefined,
      beginDate: salesOrderSearchForm.dateRange?.[0],
      endDate: salesOrderSearchForm.dateRange?.[1],
      pageindex: salesOrderPagination.pageindex,
      pagesize: salesOrderPagination.pagesize
    }
    const res = await myaxios.get('/api/SalesOrder/GetSalesOrders', { params })
    if (res.data?.success || res.data?.code === 200) {
      const payload = res.data.data || {}
      salesOrderList.value = payload.data || payload.items || []
      salesOrderPagination.total = payload.listCount || payload.total || salesOrderList.value.length
    }
  } catch (error) {
    console.error('获取销售订单失败:', error)
    ElMessage.error('获取销售订单失败')
  } finally {
    salesOrderTableLoading.value = false
  }
}

const handleSalesOrderSearch = () => {
  salesOrderPagination.pageindex = 1
  fetchSalesOrders()
}

const resetSalesOrderSearch = () => {
  salesOrderSearchForm.salesOrderNo = ''
  salesOrderSearchForm.salesOrderStatus = undefined
  salesOrderSearchForm.customerId = ''
  salesOrderSearchForm.dateRange = []
  salesOrderPagination.pageindex = 1
  fetchSalesOrders()
}

const handleSalesOrderCurrentChange = (row: SalesOrderDTO) => {
  if (!row) return
  selectedSalesOrderId.value = row.salesOrderId
  selectedSalesOrder.value = row
}

const handleSalesOrderPageSizeChange = (size: number) => {
  salesOrderPagination.pagesize = size
  salesOrderPagination.pageindex = 1
  fetchSalesOrders()
}

const handleSalesOrderPageIndexChange = () => {
  fetchSalesOrders()
}

const confirmSalesOrderSelection = async () => {
  if (!selectedSalesOrder.value) {
    ElMessage.warning('请选择销售单')
    return
  }
  const order = selectedSalesOrder.value
  form.salesOrderId = String(order.salesOrderId)
  form.salesOrderNo = order.salesOrderNo
  form.customerName = order.customerName
  form.contactInformation = order.salesContactPhone || ''
  form.receiver = order.salesContact || ''
  salesOrderDialogVisible.value = false

  await loadSalesOrderDetails(order.salesOrderId)
}

const clearSalesOrder = () => {
  form.salesOrderId = ''
  form.salesOrderNo = ''
  form.customerName = ''
  form.contactInformation = ''
  form.receiver = ''
  selectedSalesOrder.value = null
  selectedSalesOrderId.value = null
  details.value = []
  autoWarehouseOptions.value = []
  // 清空仓库选择，恢复到全部仓库列表
  form.warehouseId = ''
}

const formatSalesOrderStatus = (status: number) => {
  const option = salesOrderStatusOptions.find((item) => item.value === status)
  return option?.label ?? '未知'
}

const loadSalesOrderDetails = async (salesOrderId: number) => {
  try {
    const res = await myaxios.get('/api/SalesOrder/GetSalesOrderDetails', {
      params: { salesOrderId }
    })
    if (res.data?.success || res.data?.code === 200) {
      const rows = Array.isArray(res.data.data) ? res.data.data : res.data.data?.data || []
      if (!rows.length) {
        details.value = []
        ElMessage.warning('该销售单没有可用的明细')
        return
      }
      details.value = rows.map((item: any) => {
        const quantity = Number(item.quantity ?? item.Quantity ?? 0)
        // 从销售订单明细中获取销售单价，支持多种可能的字段名（后端返回的是 SalePrice）
        const price = Number(
          item.salePrice ??
          item.SalePrice ??  // 后端实际返回的字段名
          item.salesPrice ??
          item.SalesPrice ??
          item.unitPrice ??
          item.UnitPrice ??
          0
        )
        // 如果单价为0或不存在，尝试从金额和数量计算单价
        const calculatedPrice = price > 0
          ? price
          : (quantity > 0 ? Number((item.amount ?? item.Amount) ?? 0) / quantity : 0)
        const amount = Number((item.amount ?? item.Amount) ?? (calculatedPrice * quantity))
        const currentInventory = Number((item.currentInventory ?? item.CurrentInventory) ?? 0)
        return {
          productId: item.productId ?? item.ProductId,
          productCode: (item.productCode ?? item.ProductCode) || '',
          productName: (item.productName ?? item.ProductName) || '',
          categoryName: (item.productTypeName ?? item.ProductTypeName) || '',
          spec: (item.specificationModel ?? item.SpecificationModel) || '',
          unit: (item.unitName ?? item.UnitName) || '',
          locationName: '',
          storagelocationId: null,
          locationOptions: [],
          oldStock: currentInventory,
          deliveryPrice: calculatedPrice, // 使用计算后的单价
          deliveryNum: quantity,
          totalDeliveryPrice: amount,
          newStock: Math.max(0, currentInventory - quantity),
          inputBatch: '',
          inputTime: null,
          inputNote: (item.remark ?? item.Remark) || '',
          positionId: null,
          positionOptions: [],
          positionLoading: false,
        }
      })

      // 查询这些货品所在的仓库
      await queryWarehousesByProducts()
      details.value.forEach(detail => ensureDetailPositionMeta(detail))

      ElMessage.success(`已加载 ${rows.length} 条销售明细`)
    } else {
      details.value = []
      ElMessage.error(res.data?.message || '获取销售单明细失败')
    }
  } catch (error) {
    console.error('获取销售单明细失败:', error)
    ElMessage.warning('获取销售单明细失败')
  }
}

// 根据货品ID列表查询仓库
const queryWarehousesByProducts = async () => {
  const productIds = details.value
    .map(d => d.productId)
    .filter(id => id && id > 0) as number[]

  if (!productIds.length) {
    autoWarehouseOptions.value = []
    return
  }

  try {
    const res = await myaxios.post('/api/Outbound/GetWarehousesByProductIds', productIds)
    if (res.data?.success || res.data?.code === 200) {
      const warehouses = res.data.data || []
      autoWarehouseOptions.value = warehouses

      // 如果只有一个仓库，自动设置
      if (warehouses.length === 1) {
        form.warehouseId = String(warehouses[0].warehouseId)
        // 为每个明细查询库位
        await queryStorageLocationsForAllDetails()
      } else if (warehouses.length > 1) {
        // 多个仓库，显示下拉框让用户选择
        // 如果当前选择的仓库不在列表中，清空选择
        if (form.warehouseId && !warehouses.find((w: any) => w.warehouseId === Number(form.warehouseId))) {
          form.warehouseId = ''
        }
      } else {
        ElMessage.warning('未找到这些货品所在的仓库')
        autoWarehouseOptions.value = []
        form.warehouseId = ''
      }
    }
  } catch (error) {
    console.error('查询仓库失败:', error)
  }
}

// 为所有明细查询库位
const queryStorageLocationsForAllDetails = async () => {
  if (!form.warehouseId) return

  const warehouseId = Number(form.warehouseId)

  for (const detail of details.value) {
    if (detail.productId && detail.productId > 0) {
      await queryStorageLocationsForDetail(detail, warehouseId)
    }
  }
}

// 为单个明细查询库位
const queryStorageLocationsForDetail = async (detail: OutboundDetailRow, warehouseId: number) => {
  if (!detail.productId || detail.productId <= 0) return
  ensureDetailPositionMeta(detail)

  try {
    const res = await myaxios.get('/api/Outbound/GetStorageLocationsByProductAndWarehouse', {
      params: {
        productId: detail.productId,
        warehouseId: warehouseId
      }
    })

    if (res.data?.success || res.data?.code === 200) {
      const locations = res.data.data || []
      detail.locationOptions = locations.map((loc: any) => ({
        storagelocationId: loc.storagelocationId,
        locationName: loc.locationName,
        locationCode: loc.locationCode,
        currentStock: loc.currentStock || 0
      }))

      const matched =
        detail.storagelocationId &&
        detail.locationOptions &&
        detail.locationOptions.find(loc => loc.storagelocationId === detail.storagelocationId)

      if (matched) {
        detail.locationName = matched.locationName
        detail.oldStock = matched.currentStock
        detail.newStock = Math.max(0, matched.currentStock - (detail.deliveryNum || 0))
        await loadPositionOptionsForDetail(detail)
        return
      }

      if (locations.length === 1) {
        detail.storagelocationId = locations[0].storagelocationId
        detail.locationName = locations[0].locationName
        detail.oldStock = locations[0].currentStock || 0
        detail.newStock = Math.max(0, (locations[0].currentStock || 0) - (detail.deliveryNum || 0))
        await loadPositionOptionsForDetail(detail)
      } else if (locations.length === 0) {
        detail.locationOptions = []
        detail.storagelocationId = undefined
        detail.locationName = ''
        detail.positionId = null
        detail.positionOptions = []
      } else {
        detail.positionId = null
        detail.positionOptions = []
      }
    }
  } catch (error) {
    console.error('查询库区失败:', error)
    detail.locationOptions = []
    detail.positionOptions = []
  }
}

const fetchShelvesForWarehouse = async (warehouseId: number) => {
  if (!warehouseId) return []
  if (shelfCacheByWarehouse[warehouseId]) {
    return shelfCacheByWarehouse[warehouseId]
  }
  try {
    const res = await myaxios.get('/api/Shelf/GetShelfPage', {
      params: {
        Pageindex: 1,
        PageSize: SHELF_PAGE_SIZE,
        warehouseId,
      },
    })
    const shelves = res.data?.data?.data || res.data?.data?.items || res.data?.data || []
    const mapped = shelves.map((item: any) => ({
      shelfId: Number(item.shelfId ?? item.ShelfId ?? 0),
      shelfCode: item.shelfCode ?? item.ShelfCode ?? '',
      shelfName: item.shelfName ?? item.ShelfName ?? '',
      storagelocationId: Number(item.storagelocationId ?? item.StoragelocationId ?? 0),
    }))
    shelfCacheByWarehouse[warehouseId] = mapped
    return mapped
  } catch (error) {
    console.error('获取货架失败:', error)
    return []
  }
}

const getShelvesForLocation = async (warehouseId: number, storagelocationId: number) => {
  if (!warehouseId || !storagelocationId) return []
  const shelves = await fetchShelvesForWarehouse(warehouseId)
  return shelves.filter((shelf: any) => Number(shelf.storagelocationId) === storagelocationId)
}

const fetchPositionOptionsForShelf = async (shelf: ShelfInfo) => {
  if (!shelf?.shelfId) return []
  if (positionCacheByShelf[shelf.shelfId]) {
    return positionCacheByShelf[shelf.shelfId]
  }
  try {
    const res = await myaxios.get('/api/WarePosition/GetWarePositionPage', {
      params: {
        Pageindex: 1,
        PageSize: POSITION_PAGE_SIZE,
        shelfId: shelf.shelfId,
      },
    })
    const positions = res.data?.data?.data || []
    const options = positions
      .map((position: any) => {
        const value = Number(position.positionId ?? position.PositionId ?? 0)
        if (!value) return null
        return {
          value,
          label: buildPositionOptionLabel(shelf, position),
          shelfId: shelf.shelfId,
          shelfCode: shelf.shelfCode,
          shelfName: shelf.shelfName,
          positionCode: position.positionCode ?? position.PositionCode,
          positionRow: Number(position.positionRow ?? position.PositionRow ?? 0),
          positionColumn: Number(position.positionColumn ?? position.PositionColumn ?? 0),
          positionLayer: Number(position.positionLayer ?? position.PositionLayer ?? 0),
          positionDepth: Number(position.positionDepth ?? position.PositionDepth ?? 0),
          isFull: Number(position.isWarehouseFull ?? position.IsWarehouseFull ?? 0) === 1,
        }
      })
      .filter((option: PositionOption | null): option is PositionOption => Boolean(option))
    positionCacheByShelf[shelf.shelfId] = options
    return options
  } catch (error) {
    console.error(`获取货架 ${shelf.shelfId} 仓位失败:`, error)
    return []
  }
}

const loadPositionOptionsForDetail = async (detail: OutboundDetailRow) => {
  ensureDetailPositionMeta(detail)
  const warehouseId = Number(form.warehouseId) || 0
  const locationId = Number(detail.storagelocationId) || 0
  if (!warehouseId || !locationId) {
    detail.positionOptions = []
    detail.positionId = null
    return
  }
  detail.positionLoading = true
  try {
    const shelves = await getShelvesForLocation(warehouseId, locationId)
    if (!shelves.length) {
      detail.positionOptions = []
      detail.positionId = null
      return
    }
    const optionLists = await Promise.all(shelves.map((shelf: any) => fetchPositionOptionsForShelf(shelf)))
    detail.positionOptions = optionLists.flat()
    if (detail.positionId && !detail.positionOptions.find(opt => opt.value === detail.positionId)) {
      detail.positionId = null
    }
  } catch (error) {
    console.error('加载仓位失败:', error)
    detail.positionOptions = []
    detail.positionId = null
  } finally {
    detail.positionLoading = false
  }
}

const ensureDetailPositionOptions = (detail: OutboundDetailRow) => {
  ensureDetailPositionMeta(detail)
  if (detail.storagelocationId && (!detail.positionOptions || detail.positionOptions.length === 0)) {
    void loadPositionOptionsForDetail(detail)
  }
}

const handleDetailPositionChange = (detail: OutboundDetailRow) => {
  if (!detail) return
  ensureDetailPositionMeta(detail)
  if (!detail.positionId) return
  const option = detail.positionOptions?.find(opt => opt.value === detail.positionId)
  if (option && option.isFull === false) {
    detail.positionId = null
    ElMessage.warning('该仓位为空，无法出库')
  }
}

// 处理库位选择变化
const handleLocationChange = async (row: OutboundDetailRow) => {
  if (row.storagelocationId && row.locationOptions) {
    const selected = row.locationOptions.find(loc => loc.storagelocationId === row.storagelocationId)
    if (selected) {
      row.locationName = selected.locationName
      row.oldStock = selected.currentStock
      row.newStock = Math.max(0, selected.currentStock - (row.deliveryNum || 0))
    }
  }
  row.positionId = null
  row.positionOptions = []
  await loadPositionOptionsForDetail(row)
}

const formatDate = (value?: string) => {
  if (!value) return ''
  return moment(value).format('YYYY-MM-DD')
}

const handleLinkSalesOrderChange = (value: boolean) => {
  if (!value) {
    clearSalesOrder()
  }
}

// 处理仓库选择变化
const handleWarehouseChange = () => {
  if (form.warehouseId && details.value.length > 0) {
    queryStorageLocationsForAllDetails()
  }
}

// 监听仓库选择变化，重新查询库位
const watchWarehouseId = () => {
  if (form.warehouseId && details.value.length > 0) {
    queryStorageLocationsForAllDetails()
  }
}

// 使用watch监听仓库变化
watch(() => form.warehouseId, () => {
  watchWarehouseId()
})

// 经办人选择
const userDialogVisible = ref(false)
const userSearchKeyword = ref('')
const userLoading = ref(false)
const treeLoading = ref(false)
const allUsers = ref<any[]>([])
const filteredUsers = ref<any[]>([])
const organizationTree = ref<any[]>([])
const currentOrganizationId = ref<number | null>(null)
const selectedUser = ref<any>(null)
const selectedHandlerName = ref('')

const treeProps = {
  children: 'children',
  label: 'label'
}

const openUserDialog = () => {
  userDialogVisible.value = true
  loadOrganizations()
  loadAllUsers()
}

const loadOrganizations = async () => {
  treeLoading.value = true
  try {
    const res = await myaxios.get('/api/Organization/GetOrganizationTree', { params: { parentid: 0 } })
    if (Array.isArray(res.data)) {
      organizationTree.value = transformOrganizationTree(res.data)
    } else {
      ElMessage.error('获取组织架构失败')
    }
  } catch (error) {
    console.error('获取组织架构失败:', error)
    ElMessage.error('获取组织架构失败')
  } finally {
    treeLoading.value = false
  }
}

const transformOrganizationTree = (nodes: any[]): any[] =>
  nodes.map((node) => ({
    organizationId: node.id,
    organizationName: node.label,
    parentId: node.parentId,
    children: node.children ? transformOrganizationTree(node.children) : []
  }))

const loadAllUsers = async () => {
  userLoading.value = true
  try {
    const res = await myaxios.get('/api/Supplier/GetUser')
    if (res.data?.success || res.data?.code === 200) {
      const users = res.data.data || []
      // 确保用户对象包含 organizationId 字段（处理大小写问题）
      allUsers.value = users.map((user: any) => ({
        ...user,
        organizationId: user.organizationId || user.OrganizationId || null,
        userId: user.userId || user.UserId || null,
        userName: user.userName || user.UserName || '',
        userAccount: user.userAccount || user.UserAccount || ''
      }))
      filteredUsers.value = allUsers.value
    } else {
      ElMessage.error('获取人员列表失败')
    }
  } catch (error) {
    console.error('获取人员列表失败:', error)
    ElMessage.error('获取人员列表失败')
  } finally {
    userLoading.value = false
  }
}

const handleOrganizationClick = (data: any) => {
  const orgId = data.organizationId || data.id
  currentOrganizationId.value = orgId
  filterUsersByOrganization(orgId)
}

const filterUsersByOrganization = (orgId: number) => {
  if (orgId) {
    filteredUsers.value = allUsers.value.filter((user) => {
      const userOrgId = user.organizationId
      return userOrgId === orgId
    })
  } else {
    filteredUsers.value = allUsers.value
  }
  if (userSearchKeyword.value) {
    applySearchFilter()
  }
}

const searchUsers = () => {
  applySearchFilter()
}

const applySearchFilter = () => {
  let users = currentOrganizationId.value
    ? allUsers.value.filter((user) => user.organizationId === currentOrganizationId.value)
    : allUsers.value

  if (userSearchKeyword.value) {
    const keyword = userSearchKeyword.value.toLowerCase()
    users = users.filter(
      (user) =>
        user.userName?.toLowerCase().includes(keyword) || user.userAccount?.toLowerCase().includes(keyword),
    )
  }

  filteredUsers.value = users
}

const selectUser = (user: any) => {
  selectedUser.value = user
}

const clearSelectedUser = () => {
  selectedUser.value = null
}

const confirmUserSelection = () => {
  if (!selectedUser.value) {
    ElMessage.warning('请选择经办人')
    return
  }
  const user = selectedUser.value

  // 获取用户ID
  form.userId = String(user.userId || '')

  // 获取用户姓名
  form.handlerProple = user.userName || ''
  selectedHandlerName.value = user.userName || ''

  // 获取用户的部门ID（organizationId），根据选择的用户自动设置
  const orgId = user.organizationId
  if (orgId) {
    form.organizationId = String(orgId)
    console.log('已自动设置部门ID:', form.organizationId, '来自用户:', user.userName)
  } else {
    // 如果用户对象中没有部门ID，清空部门ID
    console.warn('用户对象中没有部门ID，用户:', user.userName)
    form.organizationId = ''
  }

  userDialogVisible.value = false
  selectedUser.value = null
  userSearchKeyword.value = ''
  currentOrganizationId.value = null
  ElMessage.success('经办人选择成功，已自动设置部门信息')
}

// 产品选择相关
const productDialogVisible = ref(false)
const productList = ref<any[]>([])
const productTableLoading = ref(false)
const selectedProducts = ref<any[]>([])
const unitOptions = ref<any[]>([])
const productSearchForm = reactive({
  productName: '',
  unitId: undefined as number | undefined,
})
const productPagination = reactive({
  pageindex: 1,
  pagesize: 10,
  total: 0,
})

const openProductDialog = () => {
  productDialogVisible.value = true
  selectedProducts.value = []
  productSearchForm.productName = ''
  productSearchForm.unitId = undefined
  productPagination.pageindex = 1
  loadUnits()
  searchProducts()
}

const loadUnits = async () => {
  try {
    const res = await myaxios.get('/api/Unit/GetUnitList')
    if (res.data?.success || res.data?.code === 200) {
      unitOptions.value = res.data.data || []
    }
  } catch (error) {
    console.error('获取单位列表失败:', error)
  }
}

const searchProducts = async () => {
  productTableLoading.value = true
  try {
    const params: any = {
      Pageindex: productPagination.pageindex,
      PageSize: productPagination.pagesize,
      number: 1,
    }
    if (productSearchForm.productName) {
      params.ProductName = productSearchForm.productName
    }
    if (productSearchForm.unitId) {
      params.UnitId = productSearchForm.unitId
    }

    const res = await myaxios.get('/api/Product/GetProduct', { params })
    if (res.data?.success || res.data?.code === 200) {
      const payload = res.data.data || {}
      productList.value = payload.data || payload.items || []
      productPagination.total = payload.listCount || payload.total || productList.value.length
    }
  } catch (error) {
    console.error('获取产品列表失败:', error)
    ElMessage.error('获取产品列表失败')
  } finally {
    productTableLoading.value = false
  }
}

const resetProductSearch = () => {
  productSearchForm.productName = ''
  productSearchForm.unitId = undefined
  productPagination.pageindex = 1
  searchProducts()
}

const handleProductSelection = (selection: any[]) => {
  selectedProducts.value = selection
}

const handleProductPageSizeChange = (size: number) => {
  productPagination.pagesize = size
  productPagination.pageindex = 1
  searchProducts()
}

const handleProductPageIndexChange = () => {
  searchProducts()
}

const confirmProductSelection = async () => {
  if (selectedProducts.value.length === 0) {
    ElMessage.warning('请选择至少一个货品')
    return
  }

  const selectedCount = selectedProducts.value.length

  // 将选中的产品添加到出库明细中
  for (const product of selectedProducts.value) {
    const detail: OutboundDetailRow = {
      productId: product.productId,
      productCode: product.productCode || '',
      productName: product.productName || '',
      categoryName: product.producttypeName || '',
      spec: product.productspecification || '',
      unit: product.productUnit || product.productspecification || '',
      locationName: '',
      storagelocationId: undefined,
      locationOptions: [],
      oldStock: Number(product.inventoryCurrtnumber || 0),
      deliveryPrice: Number(product.productInmoney || 0),
      deliveryNum: 0,
      totalDeliveryPrice: 0,
      newStock: Number(product.inventoryCurrtnumber || 0),
      inputBatch: '',
      inputTime: null,
      inputNote: '',
      positionId: null,
      positionOptions: [],
      positionLoading: false,
    }
    ensureDetailPositionMeta(detail)
    details.value.push(detail)
  }

  // 如果已选择仓库，为新增的明细查询库位
  if (form.warehouseId) {
    const newDetails = details.value.slice(-selectedCount)
    for (const detail of newDetails) {
      if (detail.productId && detail.productId > 0) {
        await queryStorageLocationsForDetail(detail, Number(form.warehouseId))
      }
    }
  }

  productDialogVisible.value = false
  selectedProducts.value = []
  ElMessage.success(`已添加 ${selectedCount} 个货品到出库明细`)
}
</script>

<style scoped>
.outbound-create {
  padding: 16px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 20px;
  font-weight: 600;
}

.readonly-input :deep(.el-input__inner) {
  background-color: #f5f7fa;
  cursor: not-allowed;
}

.summary-info {
  margin-top: 12px;
  text-align: right;
}

.empty-state {
  padding: 24px 0;
  text-align: center;
  color: #909399;
}

.search-form {
  margin-bottom: 12px;
}

.pagination-container {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: 12px;
}

.pagination-info {
  color: #606266;
}

/* 用户选择对话框样式 */
.user-selection-container {
  height: 500px;
  display: flex;
  flex-direction: column;
}

.search-section {
  margin-bottom: 16px;
  padding: 12px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.content-section {
  flex: 1;
  display: flex;
  gap: 16px;
  min-height: 0;
}

.organization-tree {
  width: 250px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  overflow: hidden;
}

.tree-header {
  padding: 12px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #e4e7ed;
  font-weight: 500;
  color: #303133;
}

.user-list {
  flex: 1;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.list-header {
  padding: 12px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #e4e7ed;
  font-weight: 500;
  color: #303133;
  display: flex;
  align-items: center;
  gap: 8px;
}

.selected-user-tag {
  margin-left: auto;
}

.user-grid {
  flex: 1;
  padding: 12px;
  overflow-y: auto;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 12px;
  align-content: start;
}

.user-item {
  display: flex;
  align-items: center;
  padding: 12px;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s;
  background-color: #fff;
}

.user-item:hover {
  border-color: #409eff;
  background-color: #ecf5ff;
}

.user-item.selected {
  border-color: #409eff;
  background-color: #ecf5ff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: #409eff;
  color: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
  font-weight: 600;
  margin-right: 12px;
}

.user-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.user-name {
  font-weight: 600;
  color: #303133;
}

.user-account {
  color: #909399;
  font-size: 12px;
}

.tree-node {
  display: inline-flex;
  align-items: center;
  padding: 4px 0;
}

.dialog-footer {
  text-align: right;
}

/* 仓库信息提示样式 */
.warehouse-info {
  display: flex;
  align-items: center;
  gap: 4px;
  margin-top: 4px;
  font-size: 12px;
  padding: 4px 8px;
  border-radius: 4px;
}

.warehouse-info.info-auto {
  color: #67c23a;
  background-color: #f0f9ff;
  border: 1px solid #b3e19d;
}

.warehouse-info.info-multiple {
  color: #e6a23c;
  background-color: #fdf6ec;
  border: 1px solid #f5dab1;
}
</style>
